package com.sunyard.domee.common.filter;

import com.sunyard.domee.common.GetBeanFactory;
import com.sunyard.domee.common.model.ResultModel;
import com.sunyard.domee.commons.constants.Contants;
import com.sunyard.domee.commons.constants.CoreConstants;
import com.sunyard.domee.commons.constants.ErrorCode;
import com.sunyard.domee.commons.model.AuthModel;
import com.sunyard.domee.commons.redis.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program domee
 * @description 过滤器
 * @author raoinyx@163.com
 * @create 2020-07-18 00:23
 */
@Slf4j
@Component
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String token = request.getHeader(Contants.TOKEN_KEY);
        RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) GetBeanFactory.getSpringEntry("redisTemplate");
        AuthModel auth = (AuthModel) redisTemplate.opsForValue().get(Keys.AUTH_TOKEN + token);

        String servletPath = request.getServletPath();
        log.info("servletPath:{}",CoreConstants.GSON.toJson(auth),servletPath);
        if(url(servletPath) || !ObjectUtils.isEmpty(auth)){
            chain.doFilter(request, response);
        }else{
            ResultModel<Object> noAuth = new ResultModel<>();
            noAuth.setCode(ErrorCode.NOT_LOGINED.getCode());
            noAuth.setMessage(ErrorCode.NOT_LOGINED.getMessage());
            response.getWriter().print(CoreConstants.GSON.toJson(noAuth));
        }
    }


    @Override
    public void destroy() {

    }

    private Boolean url(String servletUrl){
        List<String> urlList = new ArrayList<>();
        urlList.add("/service/monitor");
        int size = urlList.size();
        for(int i = 0;i <size;i++){
            if(servletUrl.indexOf(urlList.get(i))==0){
                return true;
            }
        }
        return false;
    }

}
